import * as THREE from 'three';
import * as dat from 'dat.gui';
import gsap from 'gsap';
import './index.css'


/**
 * Debug
 */
const gui = new dat.GUI({
    width: 300
})

// 轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

// Canvas
const canvas = document.querySelector("canvas.webgl");

// Scene
const scence = new THREE.Scene();

// Object
const geometry = new THREE.BoxGeometry(1, 1, 1, 2, 2, 2)

const material = new THREE.MeshBasicMaterial({
    color: '#ff0000',
    // wireframe: true
})
const mesh = new THREE.Mesh(geometry, material);
scence.add(mesh)


// Debug
gui.add(mesh.position, 'x').min(-3).max(3).step(0.01).name('Mesh x')
gui.add(mesh.position, 'y').min(-3).max(3).step(0.01).name('Mesh y')
gui.add(mesh.position, 'z').min(-3).max(3).step(0.01).name('Mesh z')


gui.add(mesh, 'visible')
gui.add(mesh.material, 'wireframe')


const debugObj = {
    color: '#ff0000',
    spin() {
        gsap.to(mesh.rotation, {
            direction: 1,
            y: mesh.rotation.y + Math.PI * 2,
        })
    },
    move(){
        gsap.to(mesh.position, {
            direction: 1,
            y: mesh.position.y + 0.5,
        })
    }
}

gui.addColor(debugObj,'color').onChange((e)=>{
   mesh.material.color.set(e)
})

gui.add(debugObj, 'spin') 
gui.add(debugObj, 'move') 



// Sizes
const Sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () => {
    // Update size
    Sizes.width = window.innerWidth
    Sizes.height = window.innerHeight

    // Update camera
    camera.aspect = Sizes.width / Sizes.height
    camera.updateProjectionMatrix()

    // Updaet renderer
    renderer.setSize(Sizes.width, Sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

// window.addEventListener('dblclick', () => {
//     const fullscreenElement = document.fullscreenElement
//     if (!fullscreenElement) {
//         canvas.requestFullscreen()
//     } else {
//         document.exitFullscreen()
//     }
// })


// Camera 
// 透视相机就是  物体离得近变大，离远变小    角度（45~75度较为合适）  宽/高   near  far(太小会导致看不全    太大看的太多，比如我们看一个村子，村子后面的山不需要看见，far需要一个合适的值)
const camera = new THREE.PerspectiveCamera(75, Sizes.width / Sizes.height, 1, 100)

// 相机的初始位置在（0，0，0）中心点，看不见物体，移动相机
camera.position.z = 3

scence.add(camera)


// Controls
const controls = new OrbitControls(camera, canvas);
// controls.enabled = false //禁用
controls.enableDamping = true  //添加阻尼效果  修改之后需要update
// controls.target.y = 1
// controls.update()


// Renderer
const renderer = new THREE.WebGLRenderer({
    canvas,
})
renderer.setSize(Sizes.width, Sizes.height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))  //解决抗锯齿,不需要超过2，避免性能浪费 

const tick = () => {
    controls.update()
    // Render
    renderer.render(scence, camera);
    window.requestAnimationFrame(tick);
}

tick()